<?php

namespace App\Http\Controllers\Admin\Finance\Payable;

use App\Http\Controllers\Controller;
use App\Models\finance\PayableDeclarationModel;
use App\Models\OrderModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class Declaration extends Controller
{
    /**
     * 单独报关列表
     */
    public function list(Request $request)
    {
        $date_start = $request->input('date_start', '');
        $date_end = $request->input('date_end', '');
        $declaration_form = $request->input('declaration_form', '');
        $type = $request->input('type', 0);
        $plate_number = $request->input('plate_number', '');
        $company_name = $request->input('company_name', '');
        $order_sn = $request->input('order_sn', '');
        $agent_id = $request->input('agent_id', 0);
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);

        $query = PayableDeclarationModel::with(['order', 'createAdmin', 'agent']);

        if ($date_start && $date_end) {
            $query->whereBetween('declaration_date', [$date_start, $date_end]);
        }

        if ($agent_id) {
            $query->where('agent_id', $agent_id);
        }

        if ($type) {
            $query->where('type', $type);
        }

        if ($declaration_form) {
            $query->where('declaration_form', $declaration_form);
        }

        if ($plate_number) {
            $query->where('plate_number', 'like', "%{$plate_number}%");
        }

        if ($company_name) {
            $query->where('company_name', 'like', "%{$company_name}%");
        }

        if ($order_sn) {
            $query->whereHas('order', function ($query) use ($order_sn) {
                $query->where('sn', 'like', "%{$order_sn}%");
            });
        }

        $total = $query->count();
        $items = $query->orderBy('id', 'desc')
            ->offset(($page - 1) * $limit)
            ->limit($limit)
            ->get()->map(function ($item) {
                return [
                    'id' => $item->id,
                    'agent_name' => $item->agent->name ?? '',
                    'declaration_date' => $item->declaration_date,
                    'type' => $item->type,
                    'type_name' => PayableDeclarationModel::TYPE_LIST[$item->type] ?? '',
                    'plate_number' => $item->plate_number,
                    'six_link_form' => $item->six_link_form,
                    'company_name' => $item->company_name,
                    'goods_name' => $item->goods_name,
                    'declaration_form' => $item->declaration_form,
                    'package_num' => $item->package_num,
                    'weight' => $item->weight,
                    'declaration_fee' => $item->declaration_fee,
                    'continuation_fee' => $item->continuation_fee,
                    'manifest_fee' => $item->manifest_fee,
                    'verification_list' => $item->verification_list,
                    'total_rmb' => $item->total_rmb,
                    'order_id' => $item->order_id,
                    'order_sn' => $item->order->sn ?? '',
                    'agent_id' => $item->agent_id,
                    'agent_name' => $item->agent->name ?? '',
                    'status' => $item->status,
                    'status_name' => PayableDeclarationModel::STATUS_LIST[$item->status] ?? '',
                    'pay_amount' => $item->pay_amount,
                    'remarks' => $item->remarks,
                    'created_at' => $item->created_at->format('Y-m-d H:i:s')
                ];
            });

        return $this->success([
            'list' => $items,
            'total' => $total,
        ]);
    }

    /**
     * 添加单独报关记录
     */
    public function add(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'declaration_date' => 'required|date',
            'type' => 'required|integer|in:1,2',
            'plate_number' => 'required|string',
            'six_link_form' => 'required|string',
            'company_name' => 'required|string',
            'goods_name' => 'required|string',
            'declaration_form' => 'required|string',
            'package_num' => 'required|integer|min:0',
            'weight' => 'required|numeric|min:0',
            'declaration_fee' => 'required|numeric|min:0',
            'continuation_fee' => 'required|numeric|min:0',
            'manifest_fee' => 'required|numeric|min:0',
            'verification_list' => 'required|numeric|min:0',
            'total_rmb' => 'required|numeric|min:0',
            'order_sn' => 'required|string',
            'agent_id' => 'required|integer|min:1',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        $order_id = 0;
        if ($request->input('order_sn')) {
            $order = OrderModel::where('sn', $request->input('order_sn'))->first();
            if (!$order) {
                return $this->error('入仓单号不存在');
            }
            $order_id = $order->id;
        }

        try {
            $declaration = new PayableDeclarationModel();
            $declaration->declaration_date = $request->input('declaration_date');
            $declaration->type = $request->input('type');
            $declaration->plate_number = $request->input('plate_number');
            $declaration->six_link_form = $request->input('six_link_form');
            $declaration->company_name = $request->input('company_name');
            $declaration->goods_name = $request->input('goods_name');
            $declaration->declaration_form = $request->input('declaration_form');
            $declaration->package_num = $request->input('package_num');
            $declaration->weight = $request->input('weight');
            $declaration->declaration_fee = $request->input('declaration_fee');
            $declaration->continuation_fee = $request->input('continuation_fee');
            $declaration->manifest_fee = $request->input('manifest_fee');
            $declaration->verification_list = $request->input('verification_list');
            $declaration->total_rmb = $request->input('total_rmb');
            $declaration->order_id = $order_id;
            $declaration->agent_id = $request->input('agent_id');
            $declaration->status = PayableDeclarationModel::STATUS_UNPAID;
            $declaration->pay_amount = 0;
            $declaration->remarks = trim($request->input('remarks', ''));
            $declaration->created_admin_id = $request->get('auth')->id;
            $declaration->save();

            return $this->success($declaration);
        } catch (\Exception $e) {
            return $this->error('添加失败：' . $e->getMessage());
        }
    }

    /**
     * 更新单独报关记录
     */
    public function update(Request $request, $id)
    {
        $declaration = PayableDeclarationModel::find($id);
        if (!$declaration) {
            return $this->error('单独报关记录不存在');
        }

        $validator = Validator::make($request->all(), [
            'declaration_date' => 'required|date',
            'type' => 'required|integer|in:1,2',
            'plate_number' => 'required|string',
            'six_link_form' => 'required|string',
            'company_name' => 'required|string',
            'goods_name' => 'required|string',
            'declaration_form' => 'required|string',
            'package_num' => 'required|integer|min:0',
            'weight' => 'required|numeric|min:0',
            'declaration_fee' => 'required|numeric|min:0',
            'continuation_fee' => 'required|numeric|min:0',
            'manifest_fee' => 'required|numeric|min:0',
            'verification_list' => 'required|numeric|min:0',
            'total_rmb' => 'required|numeric|min:0',
            'order_sn' => 'required|string',
            'agent_id' => 'required|integer|min:1',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        $order_id = 0;
        if ($request->input('order_sn')) {
            $order = OrderModel::where('sn', $request->input('order_sn'))->first();
            if (!$order) {
                return $this->error('入仓单号不存在');
            }
            $order_id = $order->id;
        }

        try {
            $declaration->declaration_date = $request->input('declaration_date');
            $declaration->type = $request->input('type');
            $declaration->plate_number = $request->input('plate_number');
            $declaration->six_link_form = $request->input('six_link_form');
            $declaration->company_name = $request->input('company_name');
            $declaration->goods_name = $request->input('goods_name');
            $declaration->declaration_form = $request->input('declaration_form');
            $declaration->package_num = $request->input('package_num');
            $declaration->weight = $request->input('weight');
            $declaration->declaration_fee = $request->input('declaration_fee');
            $declaration->continuation_fee = $request->input('continuation_fee');
            $declaration->manifest_fee = $request->input('manifest_fee');
            $declaration->verification_list = $request->input('verification_list');
            $declaration->total_rmb = $request->input('total_rmb');
            $declaration->order_id = $order_id;
            $declaration->agent_id = $request->input('agent_id');
            $declaration->remarks = trim($request->input('remarks', ''));
            $declaration->save();

            return $this->success($declaration);
        } catch (\Exception $e) {
            return $this->error('更新失败：' . $e->getMessage());
        }
    }

    /**
     * 删除单独报关记录
     */
    public function delete($id)
    {
        $declaration = PayableDeclarationModel::find($id);
        if (!$declaration) {
            return $this->error('单独报关记录不存在');
        }

        if ($declaration->status != PayableDeclarationModel::STATUS_UNPAID) {
            return $this->error('已付款的记录不能删除');
        }

        try {
            $declaration->delete();
            return $this->success(true);
        } catch (\Exception $e) {
            return $this->error('删除失败：' . $e->getMessage());
        }
    }

    /**
     * 获取单独报关详情
     */
    public function detail($id)
    {
        $declaration = PayableDeclarationModel::with(['order', 'createAdmin', 'agent'])->find($id);
        if (!$declaration) {
            return $this->error('单独报关记录不存在');
        }

        $data = $declaration->toArray();
        $data['order_sn'] = $declaration->order->sn ?? '';
        $data['agent_name'] = $declaration->agent->name ?? '';
        $data['type_name'] = PayableDeclarationModel::TYPE_LIST[$declaration->type] ?? '';
        $data['status_name'] = PayableDeclarationModel::STATUS_LIST[$declaration->status] ?? '';

        return $this->success($data);
    }

    /**
     * 设置付款状态
     */
    public function setPaid(Request $request, $id)
    {
        $declaration = PayableDeclarationModel::find($id);
        if (!$declaration) {
            return $this->error('单独报关记录不存在');
        }

        $validator = Validator::make($request->all(), [
            'pay_amount' => 'required|numeric|min:0',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        $payAmount = $request->input('pay_amount');
        $totalAmount = $declaration->total_rmb;

        // 设置付款状态
        if ($payAmount >= $totalAmount) {
            $status = PayableDeclarationModel::STATUS_PAID;
            $payAmount = $totalAmount; // 确保支付金额不超过总金额
        } elseif ($payAmount > 0) {
            $status = PayableDeclarationModel::STATUS_PART_PAID;
        } else {
            $status = PayableDeclarationModel::STATUS_UNPAID;
        }

        try {
            $declaration->pay_amount = $payAmount;
            $declaration->status = $status;
            $declaration->save();

            return $this->success($declaration);
        } catch (\Exception $e) {
            return $this->error('设置付款状态失败：' . $e->getMessage());
        }
    }
} 